import request from "@/request";
import { BASE_API_URL } from "@/config/uniConfig";
import { useUserStore } from "@/stores";

/**
 * 非流式调用（小程序等不支持 fetch 流式场景的兜底）
 */
const aiChat = async (options?: any) => {
  const data = await request({
    url: "/diagnosis/chat",
    method: "POST",
    data: options,
  });
  return data;
};

/**
 * H5 流式调用：使用 fetch + ReadableStream 读取 SSE。
 * onMessage: 每次解析到一条 data: 事件时回调，参数可能是字符串或 JSON 对象。
 */
async function aiChatStream(
  options: any,
  onMessage: (chunk: any) => void
): Promise<void> {
  // 非 H5 或没有 fetch 时，直接抛出，交由上层兜底
  // @ts-ignore
  const canStream =
    typeof window !== "undefined" && typeof fetch !== "undefined";
  if (!canStream) {
    throw new Error("STREAM_NOT_SUPPORTED");
  }

  const userStore = useUserStore();
  const url = `${BASE_API_URL}/diagnosis/chat/stream`;
  const headers: Record<string, string> = {
    Accept: "text/event-stream",
    "Content-Type": "application/json",
  };
  if (userStore.token) {
    headers.Authorization = `Bearer ${userStore.token}`;
  }

  const res = await fetch(url, {
    method: "POST",
    headers,
    body: JSON.stringify(options || {}),
  });

  if (!res.ok || !res.body) {
    throw new Error(`HTTP_${res.status}`);
  }

  const reader = res.body.getReader();
  const decoder = new TextDecoder("utf-8");
  let buffer = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });

    // 根据 SSE 规范，事件以空行分隔
    const events = buffer.split("\n\n");
    buffer = events.pop() || ""; // 保留不完整的部分

    for (const evt of events) {
      // 解析多行（可能包含 id: / event: / data: ）
      const lines = evt.split("\n");
      for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed) continue;
        if (trimmed.startsWith("data:")) {
          const payload = trimmed.slice(5).trim();
          if (payload === "[DONE]") {
            return;
          }
          try {
            const json = JSON.parse(payload);
            onMessage(json);
          } catch (_) {
            onMessage(payload);
          }
        }
      }
    }
  }
}

export { aiChat, aiChatStream };
